package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @作者 itcast
 * @创建日期 2021/11/18 11:31
 **/
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1. 参数校验  dto == null   分页参数
        dto.checkParam();
        // 2. 封装查询条件
        // 2.1 分页条件
        Page pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 2.2 查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if(dto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageReq, wrapper);
        // 3. 返回结果 PageResponseResult
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }
    // 1 待审核  2 失败  9 通过
//    @Transactional // 管理事务
    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class) // RuntimeException.class
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 1. 参数校验 (id 不能为空   )
        if(dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证的id不存在");
        }
        // 1.1 根据id查询ap_user_realname
        ApUserRealname realnameInfo = getById(dto.getId());
        if(realnameInfo == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        if(!AdminConstants.WAIT_AUTH.equals(realnameInfo.getStatus())){  // 如果不等于1 说明不是待审核状态
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证信息不是待审核状态");
        }
        // 1.2 根据ap_user_realname中关联的userId查询 ap_user
        ApUser apUser = apUserMapper.selectById(realnameInfo.getUserId());
        if(apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"改实名认证信息所关联的app账户不存在");
        }
        // 2. 修改 ap_user_realname表status状态  9
        realnameInfo.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            realnameInfo.setReason(dto.getMsg());
        }
        updateById(realnameInfo); // 修改实名认证状态
        // 3 如果状态为9
        if(AdminConstants.PASS_AUTH.equals(status)){
            // 3.1  开通自媒体账户信息
            WmUser wmUser = createWmUser(apUser);
            // 3.2  创建作者信息
            createAuthor(apUser,wmUser);
        }
        System.out.println(1/0);
        return ResponseResult.okResult();
    }


    @Autowired
    ArticleFeign articleFeign;

    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        // 1. 查询作者信息是否已经存在
        ResponseResult<ApAuthor> result = articleFeign.findByUser(apUser.getId());
        if(result.getCode().intValue() != 0){ // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        if(apAuthor != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        // 2. 如果不存在 就 创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2); // 平台自媒体人
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(apAuthor);
        if(saveResult.getCode().intValue() != 0){ // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        // 1. 根据用户名 查询 wmUser是否已经创建
       ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
       if(result.getCode().intValue() != 0){ // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
       }
        WmUser wmUser = result.getData();
       if(wmUser!=null){
           // 2. 如果已经创建 抛异常数据存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
       }
        // 3. 创建wmUser信息  保存
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId()); // 关联的app账户id
        wmUser.setNickname(apUser.getName()); // 昵称
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        if(responseResult.getCode().intValue() != 0){ // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        return responseResult.getData(); // 返回保存成功的自媒体账户信息
    }
}
